/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.application.commands;

import com.nanosn.coffeemaker.Project;
import com.nanosn.coffeemaker.freemarker.FMPP;
import com.nanosn.util.Jar;
import com.nanosn.util.parsers.commandline.Argument;
import com.nanosn.util.parsers.commandline.Command;
import java.io.File;
import java.util.HashMap;

/**
 *
 * @author selkhateeb
 */
@Argument(RegularExpression = "(startproject|sp)")
public class StartProject implements Command {

    private String getProjectName(String[] args) throws Exception {
        if (args.length < 2) {
            throw new Exception();
        }
        return args[1];
    }

    public void run(String[] args) throws Exception {

        final String projectDir = Project.PWD + File.separator + getProjectName(args);

        String srcDir = Project.TEMPLATE_FILES_PACKAGE_DIRECTORY
                        + File.separator + "application";

        /* To generate the Settings file we do not need to pass any variables
         * However, for the manage.sh we need to determine the location
         * of the Main class .. or the Jar file
         */
        HashMap<String, String> variables = new HashMap<String, String>();

        variables.put("ApplicationJar", Project.getApplicationJar().getAbsolutePath());
        variables.put("ProjectName", getProjectName(args));

        if (!Project.getApplicationJar().isDirectory()) {

            String tmpDirectory = Project.TMP + Project.TEMPLATE_FILES_PACKAGE_DIRECTORY
                                  + File.separator + "application";
            //Extract files to temp directory
            Jar.ExtractDirectory(Project.getApplicationJar(), srcDir, tmpDirectory);
            FMPP.RunFMPP(tmpDirectory, projectDir, variables);
        }
        else {
            FMPP.RunFMPP(srcDir, projectDir, variables);
        }

        /* *NIX ONLY !!! once done we need to make the manage.sh file executable
         *  TODO: Make it OS Independent
         */
        File manageSh = new File(getProjectName(args) + File.separator + "manage.sh");
        /* will looks like Mac OS JVM does not support this method so we have
         * to hack it
         */
        //Only JDK 1.6 
        //manageSh.setExecutable(true, true);

        Runtime.getRuntime().exec("chmod u+x " + projectDir + File.separator + "manage.sh");
    }

    public String getHelp() {
        return "Creates new project whith name ${value}";
    }
}
